
//
//  Untitled.swift
//  Pods
//
//  Created by zd on 25/04/1447 AH.
//
import SwiftUI

public extension Color {
    static func hex(_ value: Any, alpha: Double = 1.0) -> Color {
        Color(hex: value, alpha: alpha)
    }
    
    init(_ hex: Any, alpha: Double = 1.0) {
        self.init(hex: hex, alpha: alpha)
    }
    
    init(hex: Any, alpha: Double = 1.0) {
            var rgbValue: UInt64 = 0
            var length: Int = 0

            // 1) 整数输入：根据数值范围判定应该有几位（3 / 6 / 8）
            if let intValue = hex as? Int {
                rgbValue = UInt64(bitPattern: Int64(intValue))
                // 处理负数情况：当为负数时视为无效
                if intValue < 0 {
                    self = .clear; return
                }
                length = determineHexLength(for: rgbValue)
            } else if let uintValue = hex as? UInt64 {
                rgbValue = uintValue
                length = determineHexLength(for: rgbValue)
            } else if let uint32 = hex as? UInt32 {
                rgbValue = UInt64(uint32)
                length = determineHexLength(for: rgbValue)
            } else if let stringValue = hex as? String {
                // 2) 字符串输入：去掉空格、#、0x，然后根据字符串长度决定格式
                var hexString = stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
                if hexString.hasPrefix("#") { hexString.removeFirst() }
                if hexString.hasPrefix("0x") || hexString.hasPrefix("0X") {
                    hexString = String(hexString.dropFirst(2))
                }
                // 只保留合法字符
                hexString = hexString.uppercased()
                let validChars = CharacterSet(charactersIn: "0123456789ABCDEF")
                guard CharacterSet(charactersIn: hexString).isSubset(of: validChars) else {
                    self = .clear; return
                }

                length = hexString.count
                // 允许 3, 4, 6, 8 长度（4 可表示 RGBA 的 1 字符 each）
                if !(length == 3 || length == 4 || length == 6 || length == 8) {
                    // 如果是奇数，例如 "F7A" 已处理为 3；其他非法长度视为 clear
                    self = .clear; return
                }

                Scanner(string: hexString).scanHexInt64(&rgbValue)
            } else {
                // 不支持的类型
                self = .clear; return
            }

            // 解析不同长度
            switch length {
            case 3: // RGB 12-bit : each 1 hex digit -> expand to 2 digits
                let r = Double(((rgbValue >> 8) & 0xF) * 17) / 255.0
                let g = Double(((rgbValue >> 4) & 0xF) * 17) / 255.0
                let b = Double((rgbValue & 0xF) * 17) / 255.0
                self.init(red: r, green: g, blue: b, opacity: alpha)

            case 4: // RGBA 4-digit: each 1 hex digit
                let r = Double(((rgbValue >> 12) & 0xF) * 17) / 255.0
                let g = Double(((rgbValue >> 8) & 0xF) * 17) / 255.0
                let b = Double(((rgbValue >> 4) & 0xF) * 17) / 255.0
                let a = Double((rgbValue & 0xF) * 17) / 255.0
                self.init(red: r, green: g, blue: b, opacity: a)

            case 6: // RRGGBB
                let r = Double((rgbValue >> 16) & 0xFF) / 255.0
                let g = Double((rgbValue >> 8) & 0xFF) / 255.0
                let b = Double(rgbValue & 0xFF) / 255.0
                self.init(red: r, green: g, blue: b, opacity: alpha)

            case 8: // RRGGBBAA
                let r = Double((rgbValue >> 24) & 0xFF) / 255.0
                let g = Double((rgbValue >> 16) & 0xFF) / 255.0
                let b = Double((rgbValue >> 8) & 0xFF) / 255.0
                let a = Double(rgbValue & 0xFF) / 255.0
                self.init(red: r, green: g, blue: b, opacity: a)

            default:
                self = .clear
            }
        }
}

private func determineHexLength(for value: UInt64) -> Int {
    if value <= 0xFFF { return 3 }          // e.g. 0xF70
    else if value <= 0xFFFFFF { return 6 } // e.g. 0x0A0C18 (-> 6)
    else { return 8 }                       // treat larger as 8 (include alpha)
}
